package cn.yunyichina.provider.sb.service.impl;

import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.shangbao.SBPatientsVo;
import cn.yunyichina.provider.iface.entity.hisiface.shangbao.SBPatientsVoResponse;
import cn.yunyichina.provider.sb.dao.*;
import cn.yunyichina.provider.sb.entity.MedicalPatient;
import cn.yunyichina.provider.sb.vo.PatientRequest;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 15-AK on 2017/7/21.
 */
public class DownLoadPatientServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(DownLoadPatientServiceImpl.class);
    private MedicalPatientDao medicalPatientDao = SpringContextHandler.getBean("medicalPatientDao");
    public static int session_1_days_time_out=  60 * 24 * 60; //分钟

    public ResponseObject getPatientMessage(String data) {
        ResponseObject responseObject = new ResponseObject();
        try {
            PatientRequest patientRequest = JsonUtils.parseObject(data,PatientRequest.class);
            SBPatientsVo patientsVo = new SBPatientsVo();
            patientsVo.setHospitalCode(patientRequest.getHospitalCode());
            patientsVo.setBusinessType(patientRequest.getBusinessType());
            patientsVo.setBeginTime(patientRequest.getBeginTime());
            patientsVo.setEndTime(patientRequest.getEndTime());
            logger.info("获取商保患者信息列表his入参 patientsVo ={}",new Object[]{JsonUtils.toJsonString(patientsVo)});
            ResCommon<List<SBPatientsVoResponse>> hisfiacePatientResponse = HisifaceService.getHisifaceClient().getSBPatients(patientsVo);
            logger.info("获取商保患者信息列表his出参 hisfiacePatientResponse ={}",new Object[]{JsonUtils.toJsonString(hisfiacePatientResponse)});
            List<SBPatientsVoResponse> sBPatientsVoResponseList = hisfiacePatientResponse.getResult();
            if (!"0".equals(hisfiacePatientResponse.getResultCode())){
                if (CollectionUtils.isEmpty(sBPatientsVoResponseList)){
                    responseObject.setResultCodeAndMessage("1001","获取商保患者信息列表为空");
                }else {
                    responseObject.setResultCodeAndMessage("1999","获取商保患者信息列表his异常");
                }
                return responseObject;
            }
            logger.info("获取商保患者信息列表患者总条数:total_num ={}",sBPatientsVoResponseList.size());
            if (CollectionUtils.isNotEmpty(sBPatientsVoResponseList)){
                //medicalPatients 只会存住院或门诊其中一种业务的患者信息，因为入参 businessType限制了
                List<MedicalPatient> medicalPatients = new ArrayList<>();
                //先计算总的条数，由于返回的mzFeeId 可能返回多条
                for (SBPatientsVoResponse sbPatient :sBPatientsVoResponseList){
                    logger.info("获取商保患者信息列表sbPatient={}",new Object[]{JsonUtils.toJsonString(sbPatient)});
                    if ("1".equals(sbPatient.getBusinessType())){
                        //门诊的患者
                        String mzFeeIdList[] = sbPatient.getMzFeeId().split(",");
                        for (String mzFeeId :mzFeeIdList){
                            medicalPatients.add(buildMedicalPatient(sbPatient, mzFeeId));
                        }
                    }else{
                        //住院的患者
                        medicalPatients.add(buildMedicalPatient(sbPatient, null));
                    }
                }

                List<MedicalPatient> needInsertMedicalPatient = new ArrayList<>();
                for (MedicalPatient medicalPatient :medicalPatients){
                    String key ="";
                    StringBuilder stringBuilder = new StringBuilder();
                    if (1==medicalPatient.getBusinessType()){
                        key = stringBuilder.append(medicalPatient.getHospitalId()).append("_")
                                .append(medicalPatient.getPatId()).append("_")
                                .append(medicalPatient.getMzFeeId()).append("_")
                                .append(medicalPatient.getBusinessType()).append("_")
                                .append(medicalPatient.getVisitTime()).toString();
                    }else{
                        if (!StringUtils.isBlank(medicalPatient.getInpatientId())){
                            key = stringBuilder.append(medicalPatient.getHospitalId()).append("_")
                                    .append(medicalPatient.getPatId()).append("_")
                                    .append(medicalPatient.getInpatientId()).append("_")
                                    .append(medicalPatient.getBusinessType()).append("_")
                                    .append(medicalPatient.getVisitTime()).toString();
                        }else {
                            key = stringBuilder.append(medicalPatient.getHospitalId()).append("_")
                                    .append(medicalPatient.getPatId()).append("_")
                                    .append(medicalPatient.getAdmissionNo()).append("_")
                                    .append(medicalPatient.getInTime()).append("_")
                                    .append(medicalPatient.getBusinessType()).append("_")
                                    .append(medicalPatient.getVisitTime()).toString();
                        }
                    }
                    if(StringUtils.isBlank(CacheService.getGlobalKey("sb","patient_info",key))){
                        needInsertMedicalPatient.add(medicalPatient);
                        CacheService.setGlobalKey("sb","patient_info",key, JsonUtils.toJsonString(medicalPatient),session_1_days_time_out);
                    }
                }

                logger.info("获取商保患者信息列表needInsertMedicalPatient条数 = {}",needInsertMedicalPatient.size());
                if (CollectionUtils.isNotEmpty(needInsertMedicalPatient)){
                    //设置总条数
                    int offSet = 1;
                    for (MedicalPatient medicalPatient :needInsertMedicalPatient){
                        medicalPatient.setTotalRows(needInsertMedicalPatient.size());
                        medicalPatient.setCurrentOffset(offSet++);
                    }
                    logger.info("获取商保患者信息列表needInsertMedicalPatient ={}",new Object[]{JsonUtils.toJsonString(needInsertMedicalPatient)});
                    medicalPatientDao.batchInsert(needInsertMedicalPatient);
                }
            }

        } catch (Exception e) {
            logger.error("获取商保患者信息列表", e);
            responseObject.setResultCodeAndMessage("-1", "获取商保患者信息列表系统异常");
        }
        return responseObject;
    }

    private MedicalPatient buildMedicalPatient(SBPatientsVoResponse sbPatient,String mzfeeId){
        MedicalPatient medicalPatient = new MedicalPatient();
        medicalPatient.setId(PKGenerator.generateId());
        medicalPatient.setPatId(sbPatient.getPatId());
        medicalPatient.setOrgCode(sbPatient.getHospitalId());
        medicalPatient.setHospitalId(sbPatient.getHospitalId());
        medicalPatient.setHospitalName(sbPatient.getHospitalName());
        medicalPatient.setBusinessType((Short.parseShort(sbPatient.getBusinessType())));
        medicalPatient.setPatType((Short.parseShort(sbPatient.getPatType())));
        medicalPatient.setPatName(sbPatient.getPatName());
        medicalPatient.setPatSex(Short.parseShort(sbPatient.getPatSex()));
        medicalPatient.setPatBirth(sbPatient.getPatBirth());
        medicalPatient.setCountry(sbPatient.getCountry());
        medicalPatient.setNation(sbPatient.getNation());
        medicalPatient.setHomeTown(sbPatient.getHometown());
        medicalPatient.setMaritalStatus(Short.parseShort(sbPatient.getMaritalStatus()));
        medicalPatient.setInsuranceType(sbPatient.getInsuranceType());
        medicalPatient.setPatIdType(Short.valueOf(sbPatient.getPatIdType()));
        medicalPatient.setPatIdNo(sbPatient.getPatIdNo());
        medicalPatient.setPatCardType(Short.valueOf(sbPatient.getPatCardType()));
        medicalPatient.setPatCardNo(sbPatient.getPatCardNo());
        medicalPatient.setInpatientId(sbPatient.getInPatientId());
        medicalPatient.setAdmissionNo(sbPatient.getAdmissionNo());
        medicalPatient.setInTime(StringUtils.isBlank(sbPatient.getInTime())?null:Integer.valueOf(sbPatient.getInTime()));
        medicalPatient.setMzFeeId(mzfeeId);
        medicalPatient.setMedicalType(Short.valueOf(sbPatient.getMedicalType()));
        medicalPatient.setVisitTime(sbPatient.getVisitTime());
        medicalPatient.setPatMobile(sbPatient.getPatMobile());
        medicalPatient.setSpouseMobile(sbPatient.getSpouseMobile());
        medicalPatient.setHomepHone(sbPatient.getHomePhone());
        medicalPatient.setHomeAddress(sbPatient.getHomeAddress());
        medicalPatient.setPostCode(sbPatient.getPostCode());
        medicalPatient.setHomeTownAddress(sbPatient.getHometownAddress());
        medicalPatient.setWorkcompany(sbPatient.getWorkCompany());
        medicalPatient.setWorkPhone(sbPatient.getWorkPhone());
        medicalPatient.setEmail(sbPatient.getEmail());
        medicalPatient.setContactName(sbPatient.getContactName());
        medicalPatient.setContactPhone(sbPatient.getContactPhone());
        medicalPatient.setContactAddress(sbPatient.getContactAddress());
        medicalPatient.setContactRelationShip(sbPatient.getContactRelationship());
        medicalPatient.setGuardName(sbPatient.getGuardName());
        medicalPatient.setGuardIdType(StringUtils.isBlank(sbPatient.getGuardIdType())?null:Short.valueOf(sbPatient.getGuardIdType()));
        medicalPatient.setGuardIdNo(sbPatient.getGuardIdNo());
        medicalPatient.setCreatedTime(DateUtils.dateToString(new Date()));

        medicalPatient.setAllDataUploadCompletedFlag(new Short("0"));
        medicalPatient.setAllCheckingDwnnLoadFlag(new Short("0"));
        medicalPatient.setAllCheckingUpLoadFlag(new Short("0"));
        medicalPatient.setAllOperationDownLoadFlag(new Short("0"));
        medicalPatient.setAllOperationUpLoadFlag(new Short("0"));
        medicalPatient.setAllExaminationDownLoadFlag(new Short("0"));
        medicalPatient.setAllExaminationUpLoadFlag(new Short("0"));
        medicalPatient.setNotifyFlag(new Short("0"));
        medicalPatient.setUploadFlag(new Short("0"));
        medicalPatient.setUploadTimes(0);
        medicalPatient.setDownLoadDiagnosisFlag(new Short("0"));
        medicalPatient.setDownLoadDiagnosisTimes(0);
        medicalPatient.setDownLoadFeeFlag(new Short("0"));
        medicalPatient.setDownLoadFeeTimes(0);
        medicalPatient.setDownLoadInHospitalDiagnosisFlag(new Short("0"));
        medicalPatient.setDownLoadInHospitalDiagnosisTimes(0);
        medicalPatient.setDownLoadReportIdFlag(new Short("0"));
        medicalPatient.setDownLoadReportIdTimes(0);
        medicalPatient.setOutHospitalNotityFlag(new Short("0"));
        return medicalPatient;
    }

}
